package com.atguigu.day07;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;

public class Example8 {
    public static void main(String[] args) {
        var env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        var result = env
                // "a 1"
                // "a 2"
                // "a 10"
                .socketTextStream("localhost", 9999)
                // "a 1" ---> ("a", 1000L)
                .map(new MapFunction<String, Tuple2<String, Long>>() {
                    @Override
                    public Tuple2<String, Long> map(String in) throws Exception {
                        var arr = in.split(" ");
                        return Tuple2.of(
                                arr[0],
                                // 转换成毫秒时间戳
                                Long.parseLong(arr[1]) * 1000L
                        );
                    }
                })
                // 在map输出的数据流中插入水位线事件
                // `.assignTimestampsAndWatermarks`默认每隔200毫秒向下游发送一条水位线数据
                .assignTimestampsAndWatermarks(
                        // `Duration.ofSeconds(5)`表示设置 `最大延迟时间` 为5秒钟
                        WatermarkStrategy.<Tuple2<String, Long>>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                                .withTimestampAssigner((element, recordTimestamp) -> {
                                    return element.f1; // 告诉flink事件时间戳是f1字段
                                })
                )
                .keyBy(r -> r.f0)
                .window(TumblingEventTimeWindows.of(Time.seconds(10)))
                .allowedLateness(Time.seconds(5))
                .sideOutputLateData(new OutputTag<Tuple2<String, Long>>("late-event"){})
                .process(new ProcessWindowFunction<Tuple2<String, Long>, String, String, TimeWindow>() {
                    @Override
                    public void process(String key, Context context, Iterable<Tuple2<String, Long>> elements, Collector<String> collector) throws Exception {
                        // 使用窗口状态来表示窗口是否是第一次触发计算
                        ValueState<Boolean> flag = context.windowState().getState(
                                new ValueStateDescriptor<>(
                                        "flag",
                                        Types.BOOLEAN
                                )
                        );

                        // 获取迭代器中的元素数量
                        var count = elements.spliterator().getExactSizeIfKnown();

                        // 当水位线超过窗口结束时间时，第一次触发
                        if (flag.value() == null) {
                            collector.collect("窗口第一次触发！key：" + key + ", 窗口：" + context.window().getStart() + "~" +
                                    "" + context.window().getEnd() + ",元素数量：" + count);

                            flag.update(true);
                        } else {
                            collector.collect("窗口的迟到数据来了！key：" + key + ", 窗口：" + context.window().getStart() + "~" +
                                    "" + context.window().getEnd() + ",元素数量：" + count);
                        }
                    }
                });

        result.print("main");

        result.getSideOutput(new OutputTag<Tuple2<String, Long>>("late-event"){}).print("side");

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
